<template>
  <div class="order-container">
    <!-- 通知图标 -->
    <div class="notification-icon" @click="showNotifications = !showNotifications">
      <el-badge :value="notificationCount" :max="99" class="item">
        <i class="el-icon-bell"></i>
      </el-badge>
    </div>

    <!-- 通知面板 -->
    <el-drawer
      title="消息通知"
      :visible.sync="showNotifications"
      direction="rtl"
      size="30%"
    >
      <div class="notification-panel">
        <div class="notification-header">
          <span>未读消息 ({{ notificationCount }})</span>
          <el-button type="text" @click="clearNotifications">清空所有</el-button>
        </div>
        <div class="notification-list">
          <div
            v-for="notification in notifications"
            :key="notification.id"
            class="notification-item"
            :class="{ 'unread': !notification.read }"
            @click="markNotificationAsRead(notification)"
          >
            <div class="notification-content">
              <div class="notification-title">{{ notification.title }}</div>
              <div class="notification-message">{{ notification.content }}</div>
              <div class="notification-time">{{ notification.time }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <div class="page-header">
      <h1>工作人员订单管理</h1>
    </div>

    <!-- 查询条件 -->
    <div class="search-section">
      <el-form :inline="true" :model="query" class="search-form">
        <el-form-item>
          <label class="form-label">时间区间：</label>
          <el-date-picker
            v-model="query.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <label class="form-label">订单状态：</label>
          <el-select v-model="query.orderState" placeholder="请选择订单状态">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="已创建" :value="1"></el-option>
            <el-option label="已确认" :value="2"></el-option>
            <el-option label="已接取" :value="3"></el-option>
            <el-option label="待接取" :value="4"></el-option>
            <el-option label="已入库" :value="5"></el-option>
            <el-option label="已取消" :value="6"></el-option>

          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchOrders" icon="el-icon-search"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <div class="table-section">
      <el-table
        :data="orders"
        style="width: 100%"
        border
        stripe
        highlight-current-row
      >
        <el-table-column
          prop="orderNumber"
          label="订单编号"
          width="180"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="userName"
          label="用户姓名"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="userPhone"
          label="用户电话"
          width="150"
          align="center"
        ></el-table-column>
        <!-- <el-table-column
          prop="userAddress"
          label="预约地址"
          width="150"
          align="center"
        ></el-table-column> -->
        
        <el-table-column
          prop="startTime"
          label="预约时间"
          width="180"
          align="center"
        ></el-table-column>
        <el-table-column label="订单状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getOrderStateType(scope.row.orderState)">
              {{ getOrderState(scope.row.orderState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="totalAmount"
          label="成交金额"
          width="120"
          align="center"
        >
          <template #default="scope">
            <span class="amount">¥{{ scope.row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="creatTime"
          label="创建时间"
          width="180"
          align="center"
        ></el-table-column>
        <el-table-column label="站点" width="120" align="center">
          <template #default="scope">
            {{ getSiteName(scope.row.siteId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button
              size="mini"
              type="primary"
              @click="viewOrderDetails(scope.row)"
              icon="el-icon-view"
              >查看详情</el-button
            >
            <el-button
              size="mini"
              type="success"
              @click="acceptOrder(scope.row)"
              v-if="scope.row.orderState === 4"
              icon="el-icon-check"
              >接取订单</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="rejectOrder(scope.row)"
              v-if="scope.row.orderState === 4"
              icon="el-icon-close"
              >拒绝接单</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 查看详情对话框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ orderDetails.orderNumber }}</el-descriptions-item>
        <el-descriptions-item label="用户姓名">{{ orderDetails.userName }}</el-descriptions-item>
        <el-descriptions-item label="用户电话">{{ orderDetails.userPhone }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ orderDetails.startTime }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">{{ getOrderState(orderDetails.orderState) }}</el-descriptions-item>
        <el-descriptions-item label="成交金额">{{ orderDetails.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ orderDetails.creatTime }}</el-descriptions-item>
        <el-descriptions-item label="临时工姓名">{{ orderDetails.workName }}</el-descriptions-item>
        <el-descriptions-item label="站点名称">{{ orderDetails.siteName }}</el-descriptions-item>
        <el-descriptions-item label="用户地址" :span="2">{{ orderDetails.userAddress }}</el-descriptions-item>
      </el-descriptions>

      <div class="waste-details">
        <h3 style="margin: 20px 0;">废品详情</h3>
        <el-table 
          v-if="orderDetails.wasteList && orderDetails.wasteList.length > 0"
          :data="orderDetails.wasteList" 
          style="width: 100%"
          border
        >
          <el-table-column prop="wasteInfo" label="废品简介" min-width="120"></el-table-column>
          <el-table-column label="数量" width="100">
            <template slot-scope="scope">
              {{ scope.row.weight || '-' }} {{ scope.row.unit || '' }}
            </template>
          </el-table-column>
          <el-table-column label="单价" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.sastePrice || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="总价" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.sasteAllPrice || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="废品类型" width="100">
            <template slot-scope="scope">
              {{ getWasteTypeName(scope.row.sasteTypeId) || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="图片" width="120">
            <template slot-scope="scope">
              <el-image 
                v-if="scope.row.wasteImage"
                style="width: 60px; height: 60px; object-fit: cover;"
                :src="scope.row.wasteImage"
                :preview-src-list="[scope.row.wasteImage]">
              </el-image>
              <span v-else>无图片</span>
            </template>
          </el-table-column>
        </el-table>
        <div v-else class="no-data" style="text-align: center; padding: 20px; color: #909399;">
          暂无废品信息
        </div>
      </div>

      <!-- 新增废品信息表单，只在订单状态为已接取(3)时显示 -->
      <el-form 
        v-if="orderDetails.orderState === 3"
        :model="newWasteInfo" 
        label-width="120px" 
        class="new-waste-form"
      >
        <el-form-item label="新增废品信息">
          <div class="new-waste-section">
            <el-upload
              action="http://192.168.40.38:8080/zsd-order/order-info/upWasteImage"
              :headers="{ token }"
              :on-success="handleImageUploadSuccess"
              :before-upload="beforeImageUpload"
              list-type="picture-card"
              class="waste-upload"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <div class="waste-inputs">
              <el-select
                v-model="selectedWasteType"
                placeholder="请选择废品类型"
                style="width: 200px; margin-right: 10px;"
                @change="handleWasteTypeChange"
              >
                <el-option
                  v-for="type in wasteTypes"
                  :key="type.id"
                  :label="type.wasteTypeName"
                  :value="type.id"
                ></el-option>
              </el-select>

              <el-input
                v-model.trim="newWasteInfo.sastePrice"
                placeholder="废品单价"
                style="width: 150px; margin-right: 10px;"
                @input="validateNumber('sastePrice')"
                
              >
                <template #append>元/</template>
              </el-input>

              <el-input
                v-model.trim="newWasteInfo.weight"
                placeholder="废品数量"
                style="width: 150px; margin-right: 10px;"
                @input="validateNumber('weight')"
              ></el-input>

              <el-input
                v-model.trim="newWasteInfo.unit"
                placeholder="单位"
                style="width: 100px; margin-right: 10px;"
                :disabled="hasPresetUnit"
              ></el-input>

              <el-input
                v-model="newWasteInfo.wasteInfo"
                placeholder="废品描述"
                style="width: 200px; margin-right: 10px;"
              ></el-input>

              <el-button type="primary" @click="addNewWaste">添加</el-button>
            </div>

            <el-table :data="newWasteList" style="width: 100%; margin-top: 10px;" border>
              <el-table-column prop="wasteTypeName" label="废品类型" align="center"></el-table-column>
              <el-table-column prop="sastePrice" label="废品单价" align="center">
                <template #default="scope">
                  <span>¥{{ scope.row.sastePrice }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="weight" label="废品数量" align="center"></el-table-column>
              <el-table-column prop="unit" label="单位" align="center"></el-table-column>
              <el-table-column prop="wasteInfo" label="废品描述" align="center"></el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button type="danger" size="mini" @click="removeNewWaste(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-button
              type="success"
              @click="submitAllNewWaste(orderDetails.orderNumber)"
              style="margin-top: 10px;"
            >确认新增所有废品</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="query.pageSize"
        :page-sizes="[10, 20, 50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { webSocketClient } from '../utils/websocket';

export default {
  data() {
    return {
      query: {
        dateRange: [],
        orderState: 4,
        pageNum: 1,
        pageSize: 10,
      },
      selectedWasteType: null,
      selectedWasteTypeInfo: null,
      hasPresetPrice: false,  // 控制单价输入框禁用状态
      hasPresetUnit: false,   // 控制单位输入框禁用状态
      wasteTypes: [],
      newWasteList: [],
      orders: [],
      total: 0,
      dialogVisible: false,
      orderDetails: {
        orderNumber: '',
        userName: '',
        userPhone: '',
        startTime: '',
        orderState: null,
        totalAmount: '',
        creatTime: '',
        workName: '',
        siteName: '',
        userAddress: '',
        wasteList: []
      },
      newWasteInfo: {
        sastePrice: null,
        sasteTypeId: null,
        unit: "",
        weight: null,
        wasteInfo: "",
        wasteImage: "",
      },
      token: "your-token",
      notifications: [], // 存储通知消息
      notificationCount: 0, // 未读通知数量
      showNotifications: false, // 控制通知面板的显示状态
      siteMap: {}, // 添加站点映射对象
    };
  },
  methods: {
    // 获取订单数据
    fetchOrders() {
      const { dateRange, ...restQuery } = this.query;
      const params = {
        ...restQuery,
        startTime: dateRange && dateRange[0] ? dateRange[0] : null,
        endTime: dateRange && dateRange[1] ? dateRange[1] : null,
        pageNum: this.query.pageNum,
        pageSize: this.query.pageSize
      };

      // 移除空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === null || params[key] === undefined || params[key] === '') {
          delete params[key];
        }
      });

      axios
        .get("/zsd-order/order-info/findWorkOrder", { params })
        .then((response) => {
          if (response.data.code === 200) {
            const pageData = response.data.data;
            this.orders = pageData.records || []; // 设置订单数据
            this.total = pageData.total || 0; // 设置总条数
          } else {
            this.$message.error("查询失败：" + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("请求出错：", error);
          this.$message.error("请求出错，请稍后再试");
        });
    },

    // 获取订单状态的中文描述
    getOrderState(state) {
      const stateMap = {
        1: "已创建",
        2: "已确认",
        3: "已接取",
        4: "待接取",
        5: "已入库",
        6: "已取消",
        7: "待分配",
      };
      return stateMap[state] || "未知状态";
    },

    // 获取订单状态的类型
    getOrderStateType(state) {
      const typeMap = {
        1: "info",
        2: "success",
        3: "warning",
        4: "primary",
        5: "success",
        6: "danger",
      };
      return typeMap[state] || "info";
    },

    // 切换每页条数
    handleSizeChange(size) {
      this.query.pageSize = size;
      this.fetchOrders();
    },

    // 切换页码
    handleCurrentChange(page) {
      this.query.pageNum = page;
      this.fetchOrders();
    },

    // 查看订单详情
    async viewOrderDetails(row) {
      // 重置当前订单详情
      this.orderDetails = {
        orderNumber: '',
        userName: '',
        userPhone: '',
        startTime: '',
        orderState: null,
        totalAmount: '',
        creatTime: '',
        workName: '',
        siteName: '',
        userAddress: '',
        wasteList: []
      };
      
      // 显示对话框
      this.dialogVisible = true;
      
      try {
        // 先设置基本信息
        Object.keys(row).forEach(key => {
          this.$set(this.orderDetails, key, row[key]);
        });

        // 获取废品详情
        const wasteResponse = await axios.get('/zsd-order/order-waste/findOrderInfo', {
          params: { orderNumber: row.orderNumber }
        });
        
        if (wasteResponse.data.code === 200 && wasteResponse.data.data) {
          // 确保 wasteList 是数组
          const wasteList = Array.isArray(wasteResponse.data.data) ? wasteResponse.data.data : [wasteResponse.data.data];
          this.$set(this.orderDetails, 'wasteList', wasteList);
          console.log('废品列表已更新:', this.orderDetails.wasteList);
        }

        // 获取站点详情
        if (row.siteId) {
          const siteResponse = await axios.get('/zsd-merchant/site/find/id', {
            params: { id: row.siteId }
          });
          if (siteResponse.data.code === 200) {
            this.$set(this.orderDetails, 'siteName', siteResponse.data.data.siteName);
          }
        }

        // 获取用户地址详情
        if (row.userAddress) {
          const addressResponse = await axios.get('/zsd-user/user-address/selUserAddressById', {
            params: { id: row.userAddress }
          });
          if (addressResponse.data.code === 200) {
            this.$set(this.orderDetails, 'userAddress', addressResponse.data.data.address);
          }
        }
      } catch (error) {
        console.error('获取订单详情出错:', error);
        this.$message.error('获取订单详情失败');
      }
    },

    // 获取废品信息
    fetchWasteTypes() {
      axios
        .get("/zsd-waste/waste-type/selWasteType")
        .then((response) => {
          if (response.data.code === 200) {
            // 打印原始数据，用于调试
            console.log('原始废品类型数据:', response.data.data);
            
            // 确保每个废品类型对象都包含必要的字段
            this.wasteTypes = (response.data.data || []).map(type => ({
              ...type,
              price: type.price || type.sastePrice, // 兼容不同的价格字段名
              unit: type.unit || type.wasteUnit || '', // 兼容不同的单位字段名
            }));
            
            // 打印处理后的数据，用于调试
            console.log('处理后的废品类型数据:', this.wasteTypes);
          } else {
            this.$message.error("获取废品类型失败：" + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("请求出错：", error);
          this.$message.error("请求出错，请稍后再试");
        });
    },

    // 接取订单
    acceptOrder(row) {
      axios
        .put(
          `/zsd-order/order-info/workUpdateOrder?orderNum=${row.orderNumber}`,
          null,
          {
            headers: { token: this.token },
          }
        )
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("接取订单成功");
            this.fetchOrders(); // 刷新订单列表
          } else {
            this.$message.error("接取订单失败：" + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("请求出错：", error);
          this.$message.error("请求出错，请稍后再试");
        });
    },

    // 拒绝接单
    rejectOrder(row) {
      this.$confirm('确认拒绝接取该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/zsd-order/order-info/workNoOrder?orderNUmber=${row.orderNumber}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('已拒绝接单');
              this.fetchOrders(); // 刷新订单列表
            } else {
              this.$message.error('拒绝接单失败：' + response.data.msg);
            }
          })
          .catch(error => {
            console.error('请求出错：', error);
            this.$message.error('请求出错，请稍后再试');
          });
      }).catch(() => {
        // 取消操作，不做任何处理
      });
    },

    // 上传图片成功回调
    handleImageUploadSuccess(response) {
      if (response.code === 200) {
        this.newWasteInfo.wasteImage = response.data;
        this.$message.success("图片上传成功");
      } else {
        this.$message.error("图片上传失败：" + response.msg);
      }
    },

    // 上传图片前校验
    beforeImageUpload(file) {
      const isJPGOrPNG =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJPGOrPNG) {
        this.$message.error("只能上传 JPG 或 PNG 格式的图片");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB");
      }
      return isJPGOrPNG && isLt2M;
    },

    // 处理废品类型选择变化
    handleWasteTypeChange(value) {
      console.log('选择的废品类型ID:', value);
      const selectedType = this.wasteTypes.find(type => type.id === value);
      console.log('找到的废品类型信息:', selectedType);
      
      // 重置状态
      this.hasPresetPrice = false;
      this.hasPresetUnit = false;
      this.selectedWasteTypeInfo = selectedType || null;
      
      if (selectedType) {
        // 检查并设置单价
        if (selectedType.price !== null && selectedType.price !== undefined) {
          this.newWasteInfo.sastePrice = selectedType.price;
          this.hasPresetPrice = true;
          console.log('设置预设单价:', selectedType.price);
        } else {
          this.newWasteInfo.sastePrice = '';
        }

        // 检查并设置单位
        const unit = selectedType.unit || selectedType.wasteUnit;
        if (unit && unit.trim() !== '') {
          this.newWasteInfo.unit = unit;
          this.hasPresetUnit = true;
          console.log('设置预设单位:', unit);
        } else {
          this.newWasteInfo.unit = '';
        }

        console.log('设置后的状态:', {
          hasPresetPrice: this.hasPresetPrice,
          hasPresetUnit: this.hasPresetUnit,
          newWasteInfo: this.newWasteInfo
        });
      } else {
        // 如果没有选中类型，重置所有字段
        this.newWasteInfo.sastePrice = '';
        this.newWasteInfo.unit = '';
      }
    },

    // 重置废品信息
    resetWasteInfo() {
      this.selectedWasteType = null;
      this.selectedWasteTypeInfo = null;
      this.hasPresetPrice = false;
      this.hasPresetUnit = false;
      this.newWasteInfo = {
        sastePrice: '',
        weight: '',
        unit: '',
        wasteInfo: '',
        wasteImage: '',
      };
    },

    // 验证数字输入
    validateNumber(field) {
      const value = this.newWasteInfo[field];
      if (value === '' || value === null) return;
      
      // 只允许数字和小数点，且小数点最多一个
      if (!/^\d*\.?\d*$/.test(value)) {
        this.newWasteInfo[field] = value.replace(/[^\d.]/g, '');
      }
      
      // 处理多个小数点的情况
      const parts = this.newWasteInfo[field].split('.');
      if (parts.length > 2) {
        this.newWasteInfo[field] = parts[0] + '.' + parts.slice(1).join('');
      }
      
      // 限制小数位数为2位
      if (parts.length === 2 && parts[1].length > 2) {
        this.newWasteInfo[field] = parts[0] + '.' + parts[1].substring(0, 2);
      }
    },

    // 添加新废品时的验证
    addNewWaste() {
      if (!this.selectedWasteType) {
        this.$message.warning('请选择废品类型');
        return;
      }

      if (!this.newWasteInfo.wasteImage) {
        this.$message.warning('请先上传废品图片');
        return;
      }

      if (!this.newWasteInfo.sastePrice) {
        this.$message.warning('请输入废品单价');
        return;
      }

      if (!this.newWasteInfo.weight) {
        this.$message.warning('请输入废品数量');
        return;
      }

      if (!this.newWasteInfo.unit) {
        this.$message.warning('请输入单位');
        return;
      }

      const selectedType = this.wasteTypes.find((type) => type.id === this.selectedWasteType);
      if (!selectedType) {
        this.$message.error('无效的废品类型');
        return;
      }

      const newWaste = {
        sasteTypeId: this.selectedWasteType,
        wasteTypeName: selectedType.wasteTypeName,
        sastePrice: this.newWasteInfo.sastePrice,
        weight: this.newWasteInfo.weight,
        unit: this.newWasteInfo.unit,
        wasteInfo: this.newWasteInfo.wasteInfo,
        wasteImage: this.newWasteInfo.wasteImage,
      };

      this.newWasteList.push(newWaste);

      // 使用重置方法清空表单
      this.resetWasteInfo();
    },

    // 删除暂存的废品信息
    removeNewWaste(index) {
      this.newWasteList.splice(index, 1);
    },

    // 提交所有新增的废品信息
    submitAllNewWaste(orderNum) {
      if (this.newWasteList.length === 0) {
        this.$message.warning('请至少添加一条废品信息');
        return;
      }

      const requestBody = this.newWasteList.map((waste) => ({
        orderNum,
        ...waste,
      }));

      axios
        .post('/zsd-order/order-waste/workUpdateWaste', requestBody, {
          headers: { token: this.token },
        })
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success('新增废品信息成功');
            this.viewOrderDetails({ orderNumber: orderNum }); // 刷新订单详情
            this.newWasteList = []; // 清空暂存列表
          } else {
            this.$message.error('新增废品信息失败：' + response.data.msg);
          }
        })
        .catch((error) => {
          console.error('请求出错：', error);
          this.$message.error('请求出错，请稍后再试');
        });
    },

    // 获取废品类型列表
    async getWasteTypes() {
      try {
        const response = await this.$http.get('/zsd-waste/waste-type/list');
        if (response.data.code === 200) {
          this.wasteTypes = response.data.data;
          console.log(this.wasteTypes)
        } else {
          this.$message.error('获取废品类型列表失败：' + response.data.msg);
        }
      } catch (error) {
        console.error('获取废品类型列表出错：', error);
        this.$message.error('获取废品类型列表失败，请稍后重试');
      }
    },

    // 处理WebSocket消息
    handleWebSocketMessage(message) {
      // 如果是纯文本消息
      if (message.type === 'text') {
        this.notifications.unshift({
          id: Date.now(),
          type: 'info',
          title: '新消息',
          content: message.content,
          time: new Date().toLocaleTimeString(),
          read: false
        });
        this.notificationCount++;
        
        // 显示通知
        this.$notify({
          title: '新消息',
          message: message.content,
          type: 'info',
          duration: 5000,
          position: 'top-right'
        });
      } else {
        // 处理其他类型的消息
        this.notifications.unshift({
          id: Date.now(),
          type: message.type || 'info',
          title: message.title || '新消息',
          content: message.content,
          time: new Date().toLocaleTimeString(),
          read: false
        });
        this.notificationCount++;
        
        // 显示通知
        this.$notify({
          title: message.title || '新消息',
          message: message.content,
          type: message.type || 'info',
          duration: 5000,
          position: 'top-right'
        });
      }
    },

    // 标记通知为已读
    markNotificationAsRead(notification) {
      notification.read = true;
      this.notificationCount = this.notifications.filter(n => !n.read).length;
    },

    // 清除所有通知
    clearNotifications() {
      this.notifications = [];
      this.notificationCount = 0;
    },

    // 从token中获取用户ID的方法
    getUserIdFromToken(token) {
      try {
        const base64Url = token.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));

        const payload = JSON.parse(jsonPayload);
        return payload.id || null;
      } catch (error) {
        console.error('解析token失败:', error);
        return null;
      }
    },

    // 获取站点名称
    getSiteName(siteId) {
      return this.siteMap[siteId] || siteId;
    },

    // 获取站点列表并创建映射
    async fetchSites() {
      try {
        const response = await axios.get('/zsd-merchant/site/list', {
          params: {
            pageNum: 1,
            pageSize: 100
          }
        });
        if (response.data.code === 200) {
          const sites = response.data.data.records;
          // 创建站点映射
          this.siteMap = sites.reduce((map, site) => {
            map[site.id] = site.siteName;
            return map;
          }, {});
        } else {
          console.error('获取站点列表失败:', response.data.msg);
        }
      } catch (error) {
        console.error('请求站点列表出错:', error);
      }
    },

    // 获取废品类型名称
    getWasteTypeName(typeId) {
      const type = this.wasteTypes.find(t => t.id === typeId);
      return type ? type.wasteTypeName : typeId;
    },
  },
  mounted() {
    this.fetchOrders(); // 页面加载时自动查询
    this.fetchWasteTypes(); // 加载废品类型数据
    this.fetchSites(); // 加载站点数据

    // 获取token并连接WebSocket
    const loginUser = JSON.parse(localStorage.getItem('loginUser'));
    if (loginUser && loginUser.token) {
      // 先获取工作人员信息
      axios.get('/zsd-permission/admin-info/selAdminInfo')
        .then(response => {
          if (response.data.code === null) {
            const adminInfo = response.data.data;
            // 确保之前的连接已关闭
            if (webSocketClient.ws) {
              webSocketClient.close();
            }
            // 使用工作人员ID和token建立新连接
            webSocketClient.connect(loginUser.token, adminInfo.id);
            webSocketClient.addMessageHandler(this.handleWebSocketMessage);
          } else {
            console.error('获取工作人员信息失败：', response.data.msg);
          }
        })
        .catch(error => {
          console.error('获取工作人员信息出错：', error);
        });
    }
  },
  beforeDestroy() {
    // 组件销毁前移除消息处理器
    webSocketClient.removeMessageHandler(this.handleWebSocketMessage);
  }
};
</script>

<style scoped>
.order-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  color: #303133;
  font-size: 24px;
  font-weight: 500;
  margin: 0;
}

.search-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.form-label {
  color: #606266;
  margin-right: 10px;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: right;
}

/* 详情弹窗样式 */
.order-dialog {
  border-radius: 8px;
}

.detail-form {
  padding: 20px;
}

.detail-value {
  color: #303133;
  font-weight: 500;
}

.waste-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.new-waste-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.waste-upload {
  margin-bottom: 15px;
}

.waste-inputs {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 15px;
}

.waste-input {
  width: 100%;
}

.confirm-btn {
  align-self: flex-end;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .waste-inputs {
    grid-template-columns: 1fr;
  }
}

.notification-icon {
  position: fixed;
  top: 20px;
  right: 20px;
  cursor: pointer;
  z-index: 1000;
}

.notification-icon i {
  font-size: 24px;
  color: #606266;
}

.notification-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.notification-header {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notification-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.notification-item {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #f0f9eb;
}

.notification-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.notification-message {
  color: #606266;
  margin-bottom: 5px;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}
</style>
